package com.block.sms.service.send;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.db.entity.SmsConfigInfo;
import com.block.db.entity.SmsTemplateInfo;
import com.block.sms.dto.*;
import com.block.sms.service.ISmsSendService;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
public class XuanWuSmsServiceImpl implements ISmsSendService {


    private static final Logger log = LogFactory.getCommLog();

    @Override
    public SmsResultDTO sendSms(SmsParamDTO smsParamDTO, SmsTemplateInfo smsTemplate, SmsConfigInfo smsConfigInfo) {

        SmsResultDTO smsResultDTO = new SmsResultDTO();

        //获取短信内容
        JSONArray paramArray = smsParamDTO.getParamArray();
        String content = StrUtil.format(smsTemplate.getTemplateContent(), paramArray.stream().toArray());


        // 获取手机号数组
        String[] mobiles = new String[]{smsParamDTO.getMobie()};

        //构建请求参数
        JSONObject resultBody = new JSONObject();
        resultBody.put("batchName","玄武科技群发短信");
        resultBody.put("items", buildItems(mobiles));
        resultBody.put("content",content);
        resultBody.put("msgType", "sms");

        try {

            // 构建请求头
            Map<String, String> headers = buildHeaders(smsConfigInfo);
            //构建post请求
            String bodyResult = HttpUtil.createPost(smsConfigInfo.getSendUrl())
                    .headerMap(headers, true)
                    .body(JSON.toJSONString(resultBody))
                    .execute()
                    .body();

            // 日志打印
            log.info("【玄武短信服务】发送结束【requesturl】{}【paramMap】{}【bodyResult】{}",
                    smsConfigInfo.getSendUrl(), JSON.toJSONString(resultBody), bodyResult);

            // 解析响应结果
            JSONObject resultJson = JSON.parseObject(bodyResult);
            Integer status = resultJson.getInteger("code");
            smsResultDTO.setResult(bodyResult);
            smsResultDTO.setCode(String.valueOf(status));

            if (!ObjectUtil.equals(Integer.valueOf("0"),status)) {
                smsResultDTO.setSuccess(false);
                return smsResultDTO;
            } else {
                smsResultDTO.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            smsResultDTO.setSuccess(false);
            smsResultDTO.setResult("Error: " + e.getMessage());
        }
        return smsResultDTO;
    }


    //构建请求头
    private Map<String, String> buildHeaders(SmsConfigInfo smsConfigInfo) {
        Map<String, String> headers = new HashMap<>();

        // Content-Type
        headers.put("Content-Type", "application/json;charset=utf-8");
        // Accept
        headers.put("Accept", "application/json");
        // Authorization
        String username = smsConfigInfo.getAccountNo();
        String passwordMd5 = SecureUtil.md5(smsConfigInfo.getAccountSecret()).toLowerCase();
        String authorization = Base64.getEncoder().encodeToString((username + ":" + passwordMd5).getBytes(StandardCharsets.UTF_8));
        headers.put("Authorization", authorization);
        return headers;
    }


    // 构建items数组
    private JSONArray buildItems(String[] mobiles) {
        JSONArray items = new JSONArray();
        for (String mobile : mobiles) {
            JSONObject item = new JSONObject();
            item.put("to", mobile);
            items.add(item);
        }
        return items;
    }

    @Override
    public SmsBalanceDTO queryBalanceInfo(SmsConfigInfo smsConfigInfo) {
        return null;
    }

    @Override
    public QueryResultDTO querySendResult(QueryParamDTO queryParamDTO, SmsConfigInfo smsConfigInfo) {
        return null;
    }
}
